package com.titan.server.web.impl;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import edu.ccut.titan.component.ActionViewException;
import edu.ccut.titan.component.ComponentFactory;
import edu.ccut.titan.component.ComponentManager;
import edu.ccut.titan.component.IComponent;
import edu.ccut.titan.component.IParameterContext;

/**
 * 
 * @author LeslieGu
 *
 */
public class WebHelper {

    private HttpServletRequest request;

    private HttpServletResponse response;

    private HttpSession session;

    public WebHelper(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
        this.session = request.getSession();
    }

    public HttpServletRequest getRequest() {
        return request;
    }

    public HttpServletResponse getResponse() {
        return response;
    }

    public HttpSession getSession() {
        return session;
    }

    /**
     * TODO 一个简单的版本实现
     *
     * @return
     */
    public String execute() throws Exception {
    	String componentFullKey = this.getActionKey(this.getRequest().getRequestURI());
        IComponent action = ComponentManager.getInstance().getComponent(componentFullKey);

        IParameterContext parameterContext = ComponentFactory.createParameterContext();
        
        parameterContext.addParameter(this.request, HttpServletRequest.class);
        parameterContext.addParameter(this.response, HttpServletResponse.class);
        
        
        try {
			action.execute(parameterContext);
		} catch (ActionViewException e) {
			return e.getViewLocation();
		}

        return "一个错误页";
    }

    private String getActionKey(String requestURI) {
        return requestURI.substring(requestURI.indexOf("/", 1) + 1);
    }
}
